package com.thh.idempotent.util;

import com.thh.idempotent.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @description:
 * @author: thh
 * @time: 2020/6/7 9:33
 */
@Component
public class TokenUtil {
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 创建token
     *
     * @return
     */
    public String createToken() {
       // String str = RandomUtil.randomUUID();
        String str = UUID.randomUUID().toString().replace("-", "");
        StringBuilder token = new StringBuilder();
        try {
            token.append(Constant.TOKEN_PREFIX).append(str);
            redisUtil.setEx(token.toString(), token.toString(), 10000L);
            boolean notEmpty = !StringUtils.isEmpty(token.toString());
            if (notEmpty) {
                return token.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 检验token
     *
     * @param request
     * @return
     */

    public boolean checkToken(HttpServletRequest request) throws Exception {

        String token = request.getHeader(Constant.TOKEN_NAME);
        if (StringUtils.isEmpty(token)) {// header中不存在token
            token = request.getParameter(Constant.TOKEN_NAME);
            if (StringUtils.isEmpty(token)) {// parameter中也不存在token
                throw new Exception ("parameter中也不存在token");
            }
        }

        if (!redisUtil.exists(token)) {
            throw new Exception ("重复提交");
        }

        boolean remove = redisUtil.remove(token);
        if (!remove) {
            throw new Exception ("重复操作");
        }
        return true;
    }
}


